package com.ahdy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${tts.save-dir}")
    private String ttsAudioDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取音频文件目录
        File audioDirectory = new File(ttsAudioDir);

        // 确保目录存在
        if (!audioDirectory.exists()) {
            boolean created = audioDirectory.mkdirs();
            log.info("创建音频目录: {} - {}", audioDirectory.getAbsolutePath(), created ? "成功" : "失败");
        }

        // 检查目录权限
        log.info("音频目录状态:");
        log.info(" - 路径: {}", audioDirectory.getAbsolutePath());
        log.info(" - 存在: {}", audioDirectory.exists());
        log.info(" - 可读: {}", audioDirectory.canRead());
        log.info(" - 可写: {}", audioDirectory.canWrite());

        // 列出目录中的文件
        File[] files = audioDirectory.listFiles();
        if (files != null && files.length > 0) {
            log.info("目录中的文件:");
            for (File file : files) {
                log.info(" - {} ({}bytes)", file.getName(), file.length());
            }
        } else {
            log.info("目录为空");
        }

        // 配置资源映射
        String location = "file:" + audioDirectory.getAbsolutePath().replace("\\", "/") + "/";
        log.info("配置资源映射: /tts-audios/** -> {}", location);

        registry.addResourceHandler("/tts-audios/**")
                .addResourceLocations(location);
    }
}